<template>
    <div class="control list_container flex both-100">
        <Breadcrumb :title="pageTitle" />
        <div class="content_container">
            <!-- 搜索 -->
            <el-form ref="searchForm" :model="searchMap" class="search_wrapper flex-space-between">
                <div class="search flex">
                    <el-form-item prop="planName" size="small">
                        <el-input v-model="searchMap.planName" placeholder="计划名称"></el-input>
                    </el-form-item>
                    <el-form-item class="flex">
                        <el-button @click="handleSearch()" class="btn_primary el-icon-search">查询</el-button>
                        <el-button @click="handleReset()" class="btn_cancel el-icon-refresh-left">重置</el-button>
                    </el-form-item>
                </div>
                <div class="edit">
                    <el-form-item class="flex">
                        <el-button @click="handleAdd()" class="btn_primary el-icon-plus">新增</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <div class="table_container">
                <!-- 表格 -->
                <el-table :data="dataList" v-loading="loading" stripe class="per_table" style="width: 100%"
                    :height="winTableH">
                    <el-table-column prop="planName" label="计划名称"></el-table-column>
                    <el-table-column prop="joinUsers" label="风险识别人员" align="center">
                        <template slot-scope="scope">
                            <span>{{ scope.row.joinUsers.map(item => item.nickName).join(', ') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="joinUserIds" label="风险识别参与人员" align="center">
                        <template slot-scope="scope">
                            <span>{{ getUserNamesByIds(scope.row.joinUserIds, userOptions) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="identifyLocation" label="风险识别地点" align="center"></el-table-column>
                    <el-table-column prop="taskStatus" label="状态" align="center">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.identify_task_status" :value="scope.row.taskStatus" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="280" align="center">
                        <template slot-scope="scope">
                            <div>
                                <span type="text" class="tag_primary" size="small"
                                    @click="handleSelect(scope.row)">查看</span>
                                <span type="text" class="marginl-10 tag_warning" size="small"
                                    @click="handleDelete(scope.row)">删除</span>
                                <span v-show="scope.row.taskStatus === '1'" type="text" class="marginl-10 tag_primary"
                                    size="small" @click="handleEdit(scope.row)">完成风险识别任务</span>
                                <span v-show="scope.row.taskStatus === '0'" type="text" class="marginl-10 tag_primary"
                                    size="small" @click="handleEditPush(scope.row)">推送风险识别任务</span>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize"
                @change="getList"></Pagination>

        </div>
        <!-- 弹窗 详情 -->
        <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisible" width="800" append-to-body
            :before-close="() => { dialogVisible = false }" :close-on-click-modal="false">
            <div class="content">
                <el-form ref="form" :model="formModel" size="small" :rules="formRules" label-width="80px"
                    :disabled="title === '风险点详情'">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="计划名称" label-width="120px" prop="planName">
                                <!-- <el-input v-model="formModel.planName" placeholder=""></el-input> -->
                                <el-select v-model="formModel.riskIdentifyPlanId" placeholder="" style="width: 100%;"
                                @change="optionHanle">
                                    <el-option v-for="(item, index) in planDataList" :label="item.planName"
                                        :value="item.riskIdentifyPlanId"
                                        ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="风险识别人员" label-width="120px" prop="identifyUserIds">
                                <el-select v-model="formModel.identifyUserIds" multiple placeholder="请选择人员"
                                    style="width: 100%;">
                                    <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                                        :value="item.userId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="风险识别参与人员" label-width="120px" prop="joinUserIds">
                                <el-select v-model="formModel.joinUserIds" multiple placeholder="请选择人员"
                                    style="width: 100%;">
                                    <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                                        :value="item.userId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="风险识别地点" label-width="120px" prop="identifyLocation">
                                <el-input v-model="formModel.identifyLocation" placeholder=""></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注" label-width="120px">
                                <el-input v-model="formModel.remark" type="textarea" placeholder=""></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

            </div>
            <div slot="footer" class="dialog-footer" v-if="title === '风险识别任务详情'">
                <el-button @click="() => { dialogVisible = false }" class="btn_cancel">关 闭</el-button>
            </div>
            <div slot="footer" v-else class="dialog-footer">
                <el-button @click="() => { dialogVisible = false }" class="btn_cancel">取 消</el-button>
                <el-button type="primary" @click="submitFrom()" class="btn_primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="title" :visible.sync="dialogVisibleInfo" width="800" append-to-body>
            <custom-title title="详细信息" />
            <BaseDescriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="formModel">
            </BaseDescriptions>
        </el-dialog>
    </div>
</template>
<script>
import { riskIdentifyTask, riskIdentifyTaskList, riskIdentifyTaskInfo, riskIdentifyTaskFinish, riskIdentifyTaskPush, riskIdentifyPlanList } from '../api/index'
import { listUser, deptTreeSelect } from '@/api'

export default {
    dicts: ['control_hierarchy', 'identify_task_status'],
    data() {
        return {
            pageTitle: '风险识别任务',
            loading: true,
            total: 0,
            reqType: 'post',
            title: '风险识别任务',
            dialogVisible: false,
            dialogVisibleInfo:false,
            deptOptions: undefined,
            userOptions: [],
            searchMap: {
                pageNum: 1,
                pageSize: 10,
            },
            descConfig: {
                size: 'medium',
                column: '2',
            },
            dataList: [],
            // 提交表单数据
            formModel: {},
            formRules: {},
            planDataList: [],
            descConfigItem: [
                {
                    fieIdName: 'planName',
                    label: '计划名称',
                    span: 2,
                },
                {
                    fieIdName: 'identifyUserIdName',
                    label: '风险识别人员',
                    span: 2,
                },
                {
                    fieIdName: 'joinUserIdName',
                    label: '风险识别参与人员',
                    span: 2,
                },
                {
                    fieIdName: 'identifyLocation',
                    label: '风险识别地点',
                    span: 2,
                },
            ]
        }
    },
    methods: {
        submitFrom() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    riskIdentifyTask(this.formModel, this.reqType).then(res => {
                        if (200 === res.code) {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                            });
                            this.dialogVisible = false
                            this.formModel = {}
                            this.getList()
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        //删除
        handleDelete(row) {
            this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                riskIdentifyTask([row.riskIdentifyTaskId], 'delete').then(res => {
                    if (200 === res.code) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList()
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 查询
        handleSearch() {
            this.getList()
        },
        // 重置
        handleReset() {
            this.searchMap = {
                pageNum: 1,
                pageSize: 10,
            }
            this.getList()
        },
        handleAdd() {
            this.title = "新增风险识别任务"
            this.reqType = 'post'
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
            this.formModel = {
                projectPointId: this.$route.query.projectPointId, //项目点id
                projectPointRiskId: this.$route.query.projectPointRiskId,//风险点id
            }
            console.log(this.formModel)
            this.dialogVisible = true;
        },
        //完成识别任务
        handleEdit(row) {
            riskIdentifyTaskFinish(row).then(res => {
                if (200 === res.code) {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                    });
                    this.getList()
                }
            });
        },
        //推送识别任务
        handleEditPush(row) {
            riskIdentifyTaskPush(row).then(res => {
                if (200 === res.code) {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                    });
                    this.getList()
                }
            });
        },
        //查看
        handleSelect(row) {
            this.title = "风险识别任务详情"
            // riskIdentifyTaskInfo(row.riskIdentifyPlanId).then(res => {
            //     this.formModel = res.data
            //     this.dialogVisible = true;
            // });
            this.formModel = row
            this.dialogVisibleInfo = true;
            
            this.formModel.joinUserIdName = this.selectedNickNames(row.joinUserIds)
            this.formModel.identifyUserIdName = this.selectedNickNames(row.identifyUserIds)

        },
        selectedNickNames(val) {
            if (Array.isArray(val)) {
                return val
                    .map(userId => this.userOptions.find(item => item.userId === userId)?.nickName)
                    .filter(Boolean) // 过滤掉undefined
                    .join(', ');
            }

        },
        // 页面数据
        async getList() {
            const { code, rows, total } = await riskIdentifyTaskList(this.searchMap)
            if (code === 200) {
                this.loading = false
                this.dataList = rows
                this.total = total
            }
        },
        // 计划数据
        async getPlanList() {
            const { code, rows, total } = await riskIdentifyPlanList(this.searchMap)
            if (code === 200) {
                this.planDataList = rows
                console.log(this.planDataList)
            }
        },
        getUserNamesByIds(ids, userList) {
            return ids.map(id => userList.find(user => user.userId === id)?.nickName || '').join(', ');
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        optionHanle(val){
            let deptId = ''
            this.planDataList.forEach(element => {
                if(element.riskIdentifyPlanId === val){
                   deptId = element.deptId
                }
            });
            console.log(deptId)
        this.initUserList(deptId)
        },
        // 用户列表
        initUserList(deptId) {
            listUser({deptId:deptId}).then(res => {
                const resp = res
                this.userOptions = resp.rows
            })
        }
    },
    mounted() {
        console.log(this.$route.query)
        this.formModel.projectPointId = this.$route.query.projectPointId
        this.formModel.projectPointRiskId = this.$route.query.projectPointRiskId
        this.getList()
        this.getPlanList()
        this.getDeptTree()
    },
}
</script>
<style lang="less">
.control {
    .el-table__cell {
        .cell {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}
</style>